import React, { Component } from 'react';
import { NavigationEvents } from 'react-navigation';
import {
  StyleSheet, Text, View, TouchableOpacity,
  Image, PixelRatio, FlatList, Alert, Animated
} from "react-native";
import { API, API_GENERATE } from '../../../../config/api';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import HTTP from '../../../../utils/http';
import ToastUtil from '../../../../utils/toast';
import OrderDetailsService from '../../../order-new/details/_common/service';
import { Common } from '../../../../component/common/Common';
import { CartoonComponent } from '../detail/cartoonPage';
import { NewAccount } from '../../../../components/common/newAccount';
import { SlideSelect } from '../../../../components/common/slideSelect';
import { RefuseModal } from '../../../../component/ModalVerifylComponent.js';
import { ProgressModal } from '../../../../components/common/ProgressModal';

const scale = GLOBAL.SCALE;
const correct = require('../../../../imgs/global/correct.png');

const LIST = [
  {
    label: '长约计划',
  },
  {
    label: '临采计划',
  },
]

export class BusinessPlanPage extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      headerTitle: '经营计划审批详情',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      // headerRight: ,
      headerStyle: style.head.headerStyle,
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center',
      }
    }
  };

  constructor(props) {
    super(props);
    this.itemData = this.props.navigation.state.params || {};
    console.log(this.itemData)
    this.state = {
      tabIndex: 0,
      tabItem: 0,
      status: 'data',
      refreshIcon: false,
      listData: [],
      itemAuditingletedCnt: '0',
      itemAuditRejectCntCnt: '0',
      alertShow: false,
      options: [],
      classifyVal: '',
      PlannedMonth: '',
      resLongCount: 0,
      resQuantity: 0,
      resNormalList: [],
      resNormalCount: 0,
      resCount: 0,
      corpId: '',
      resDetaiList: [], // 长约列表
      Quantity: '', // 数量
      organs: [],
      branch: {},
      organIds: [],
      section: false,
      isHeight: true,
      startHeight: 0,
      isLock: false,
      isSelect: false,
      countMber: 0, // 数量总和
      countNum: 0, // 统计值
      lightBoxData: {
        modalVisible: false,
        onClosePress: this._closeLightBox,
        title: '',
        rowDataList: [],
      },
      isTab: false,
      // heightObj: new Animated.Value(0),
    }
    this.onOff = true;
    this.reload = true; // 判断是整个页面刷新还是下拉刷新
    this.pageParams = {
      pageNo: 1,
      pageSize: 10,
    }
  }

  async componentDidMount () {
    await this._initType();
    await this._initTime();
    await this.initPage();
  }

  // 根据采销类型确定文本
  _initType = () => {
    if (this.itemData.orderType == "S") {
      LIST.forEach((item, index) => {
        if (item.label == '临采计划') {
          item.label = '分销计划'
        }
      })
    } else {
      LIST.forEach((item, index) => {
        if (item.label == '分销计划') {
          item.label = '临采计划'
        }
      })
    }
  }
  //  默认初始时间
  _initTime = () => {
    const date = new Date;
    const year = date.getFullYear();
    const month = ('0' + (date.getMonth() + 1)).substr(-2);
    const time = year + month; // 默认当前月份传的参数
    const times = year + '-' + month;
    this.pageParams.planMonthTime = times;
    this.pageParams.planTime = time;
  }

  //

  initPage = async (refreshIcon) => {
    let { tabIndex, organs, branch, section, isSelect, isTab } = this.state
    let arrAyy = [];
    let ary = [];
    if (isSelect) {
      ary.push(branch.organId)
    }
    if (section) {
      for (let j = 0; j < this.itemData.organs.length; j++) {
        if (branch.corpName == this.itemData.organs[j].organName) {
          arrAyy.push(this.itemData.organs[j].organId)
        }
      }
    } else {
      for (let i = 0; i < this.itemData.organs.length; i++) {
        arrAyy.push(this.itemData.organs[i].organId)
        this.itemData.organs[i]['corpName'] = this.itemData.organs[i].organName
      }
    }
    this.setState({
      status: this.reload ? 'loading' : 'data',
      refreshIcon: !this.reload,
      organs: this.itemData.organs,
      isLock: false,
    })
    let goodsId = [];
    goodsId.push(this.itemData.goodsCateId)
    this.params = {
      planMonth: this.itemData.planMonth ? this.itemData.planMonth : this.pageParams.planTime,
      corpId: this.itemData.corpId,
      bizClass: this.itemData.bizClass,
      goodsCateId: this.itemData.goodsCateId,
      goodsCateIds: goodsId,
      orderType: this.itemData.orderType,
      organIds: isSelect ? ary : arrAyy
    };
    // console.log('this.params', this.params)
    let resTistData = await HTTP.POST(API_GENERATE(API.PLAN_AETAIL_LIST), this.params)
    if (resTistData) {
      let resLongCount = resTistData.longOrderApplyDetail.count || 0//长约计划数 totalQuantity
      let resQuantity = resTistData.longOrderApplyDetail.totalQuantity || 0 // 长约合计量
      let resDetaiList = resTistData.longOrderApplyDetail.detailList || [] // 长约列表
      let resNormalCount = resTistData.normalApplyDetail.count || 0// 临采计划数
      let resCount = resTistData.normalApplyDetail.totalQuantity || 0 // 临采合计量
      let resNormalList = resTistData.normalApplyDetail.detailList || [] // 临采列表
      for (var k = 0; k < resDetaiList.length; k++) {
        resDetaiList[k]['isCheck'] = false;
      }
      for (var g = 0; g < resNormalList.length; g++) {
        resNormalList[g]['isCheck'] = false;
      }
      if (isTab == false) {
        if (resLongCount > 0) {
          this.state.tabIndex = 0
        } else {
          if (resNormalCount > 0) {
            this.state.tabIndex = 1
          } else {
            this.state.tabIndex = 0
          }
        }
      }

      this.setState({
        listData: this.state.tabIndex == 0 ? resDetaiList : resNormalList,
        status: this.state.tabIndex == 0 ? resDetaiList && resDetaiList.length > 0 ? 'data' : 'empty' : resNormalList && resNormalList.length > 0 ? 'data' : 'empty',
        refreshIcon: false,
        Quantity: this.state.tabIndex == 0 ? resQuantity : resCount,
        resLongCount: resLongCount, // 长约计划数
        classifyVal: this.itemData.goodsCateName,
        PlannedMonth: this.itemData.PlannedMonth,
        resNormalCount: resNormalCount,// 临采计划数
        resNormalList: resNormalList, // 临采列表
        resDetaiList: resDetaiList, // 长约列表
        isTab: true,
      })
    } else {
      this.setState({
        status: 'error'
      })
    }
  }

  // 审批流
  _btnRaido = async (data) => {
    // console.log(data.itemId, '98777667', data.processInstanceId, data.corpId)
    let responseData9 = await OrderDetailsService.checkApprovalFlow(data.itemId, 'PLAN_APPLY', data.processInstanceId, data.corpId);
    responseData9 = responseData9 && responseData9.map((item) => {
      if (item.auditResult == 9) {
        item.auditResultName = '操作';
      }
      return item;
    })
    let { lightBoxData } = this.state;
    lightBoxData.modalVisible = true;
    lightBoxData.title = '审批状态';
    lightBoxData.rowDataList = responseData9;
    this.setState({
      lightBoxData,
      status: 'data'
    })
  }
  _closeLightBox = () => {
    let { lightBoxData } = this.state;
    lightBoxData.modalVisible = false;
    this.setState({ lightBoxData });
  }


  loadMore = () => {
    this.reload = false;
    this.initPage();
  }

  refresh = () => {
    this.reload = false;
    this.initPage();

  }
  //切换
  _tabFn = (items, tabIndex) => {
    this.reload = true;
    this.setState({
      tabIndex,
    }, () => {
      this.initPage();
    })
  }

  onErrorRefresh = () => {
    let { tabIndex } = this.state;
    if (tabIndex != 2) {
      this.initPage();
    }
  }

  // 审批
  approve = async () => {
    const { listData, isLock, countNum } = this.state;
    // if (this.requesting) return;
    this.setState({ showRejectModal: false });
    // this.requesting = true;
    let sel = [];// 
    let arr = []
    listData && listData.forEach((item, i) => {
      if (item.isCheck == true) {
        let bukey = {};
        bukey['businessKey'] = item.itemId;
        bukey['taskId'] = item.taskId;
        arr.push(bukey)
      }
    })
    let requestParams = {
      orderType: this.params.orderType,
      workFlows: arr,
      remark: this.remark,
      status: this.auditResult == 1 ? 'PASS' : 'REJECT'
    };
    if (requestParams.workFlows && requestParams.workFlows.length < 1) {
      ToastUtil.showSuccess(`请先勾选`)
      return
    }
    let text = this.auditResult ? '同意' : '驳回';
    this.setState({ status: 'loading' });
    let res = await HTTP.POST(API_GENERATE(API.PLAN_APPLY_AUDIT), requestParams);
    // this.requesting = false;
    if (res) {
      ToastUtil.showSuccess(`${text}成功`).then(() => {
        this.initPage();
        this.setState({
          isLock: false,
          countNum: 0,
        })
      })
    } else {
      this.setState({
        status: 'data'
      })
    }
  }
  // 选中 某个 或者部分
  checkFrozen = (i, isCheck) => {
    this.state.listData[i].isCheck = !isCheck;
    this.setState({
      listData: this.state.listData
    })
    let isLocks = true;
    let ssry = [];
    let countMber = 0;
    this.state.listData.forEach((item, i) => {
      if (item.isCheck == false) {
        isLocks = false;
      } else if (item.isCheck == true) {
        ssry.push(item)
        countMber += item.planQuantity
      }
    })
    // console.log(ssry, '这是选中数据', countMber)
    this.setState({
      isLock: isLocks,
      countNum: ssry ? ssry.length : 0,
      countMber: countMber,
    })
  }
  // 全选
  checkWhole = (isLock) => {
    let { listData, countMber } = this.state
    let countN = listData.length;
    countMber = 0;
    listData.forEach((item, i) => {
      item.isCheck = !isLock;
    })
    if (isLock == true) {
      countN = 0;
      countMber = 0;
    } else {
      listData.forEach((items, ) => {
        countMber += items.planQuantity;
      })
    }
    this.setState({
      isLock: !isLock,
      listData,
      countNum: countN,
      countMber,
    })

  }
  // 全选
  _renderApprove = () => {
    let { showRejectModal, isLock, status, listData, countNum, countMber } = this.state;
    return (
      <View>
        {status != 'data' ? (
          <View></View>
        ) : (
            <View style={styles.flexWhole}>
              <TouchableOpacity style={styles.flexRow} onPress={() => this.checkWhole(isLock)}>
                <View style={styles.lockView}>
                  {isLock ? <Image style={styles.lockImage} source={correct} /> : null}
                </View>
                <View style={{ alignItems: 'center' }}>
                  <Text style={styles.itemLightText}>已全选 {countNum},数量{countMber.toFixed(2)}吨</Text>
                </View>
              </TouchableOpacity>
              <View style={styles.itemDayTime}>
                <Text style={[styles.consent,]} onPress={() => {
                  this.auditResult = 1;
                  this.remark = '';
                  this.setState({
                    showRejectModal: true,
                    listData,
                  })
                  // this.consentCreate(item)
                }}>同意</Text>
                <Text style={styles.itemdown} onPress={() => {
                  if (listData) {
                    this.auditResult = 0;
                    this.remark = '';
                    this.setState({
                      showRejectModal: true,
                      listData
                    })
                  } else {
                    ToastUtil.showWarning('没有数据')
                  }
                }}>驳回</Text>
              </View>
            </View>
          )}
      </View>
    )
  }
  _approvalListItim = (data) => {

    let { listData } = this.state
    this.listMethodData = {
      data: data,
      onBtnRaido: this._btnRaido,// 查看审批流
      onCheckFrozen: this.checkFrozen, // 选择按钮
      listData: listData,
      teamName: this.itemData.teamName ? this.itemData.teamName : ''
    }
    return <CartoonComponent {...this.listMethodData} />
  }

  render () {
    let { tabIndex, listData, refreshIcon, status, organs, branch,
      alertShow, Quantity, showRejectModal, classifyVal,
      PlannedMonth, resLongCount, resNormalCount } = this.state;
    let { lightBoxData } = this.state || {};
    return (
      <View style={styles.container}>
        <NavigationEvents onWillFocus={async () => {
        }} />
        <View style={styles.flexBox}>
          <View style={styles.flexDate}>
            <Text style={styles.flexMonth}>计划月份：</Text>
            <Text style={styles.flexDateTime}>{PlannedMonth ? PlannedMonth.substr(0, 4) + "-" + PlannedMonth.substr(4) : this.pageParams.planMonthTime}</Text>
          </View>
          <View style={styles.flexType}>
            <Text style={styles.flexBusiness}>业务类型：</Text>
            <Text style={styles.flexContent}>{this.itemData.itemizeName || '--'}</Text>
          </View>
        </View>
        <View style={styles.flexRefer}>
          <Text style={styles.flexBranch}>提交部门：</Text>
          <View style={
            this.itemData.lineName && this.itemData.lineName.length > 5 || this.itemData.teamName && this.itemData.teamName.length > 4
              ? styles.flexSection : styles.flexBranchtitle
          }>
            <Text style={styles.flexSectionName}>
              {this.itemData.corpName ? this.itemData.corpName + ' | ' : '--'}
              {this.itemData.lineName ? this.itemData.lineName + ' | ' : '--'}
              {this.itemData.teamName ? this.itemData.teamName + ' | ' : '--'}
            </Text>
            <View style={
              this.itemData.lineName && this.itemData.lineName.length > 5 || this.itemData.teamName && this.itemData.teamName.length > 4
                ? styles.flexBranchName : styles.flexBranchText
            }>
              <NewAccount fn={(val) => { this.setState({ alertShow: val, isSelect: true }) }} choice={branch.corpName ? branch.corpName : '全部部门'} />
            </View>
          </View>

        </View>
        <View style={styles.flexClassify}>
          <Text style={styles.flexVaule}>分类：</Text>
          <Text style={styles.flexProuct}>{classifyVal || '--'}</Text>
        </View>
        <View style={styles.headBox}>
          {LIST.map((items, index) => {
            return (
              <View key={index}>
                <Text onPress={() => { this._tabFn(items, index) }} style={[styles.tabItems, tabIndex == index ? styles.tabItemActive : null]}>{items.label} {index == 0 ? resLongCount : resNormalCount}
                </Text>
                {tabIndex == index ? (
                  <Text style={{
                    height: 1 * scale, backgroundColor: '#0E7FFD', flexDirection: 'row', paddingLeft: 10 * scale,
                    paddingRight: 10 * scale,
                  }}>
                  </Text>
                ) : null
                }
              </View>
            )
          })
          }
        </View>
        {
          status == 'data' ? (
            <View style={styles.body}>
              <View style={{ flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center', paddingLeft: 15 * scale, marginTop: 20 * scale }}>
                <Text style={styles.flexCount}>合计量：</Text>
                <Text style={{ color: '#000000', fontSize: 10 * scale }}>{(Quantity || 0).toFixed(3)}吨</Text>
              </View>
              <FlatList
                data={listData}
                renderItem={
                  this._approvalListItim
                }
                refreshing={refreshIcon}
                onRefresh={() => { this.refresh() }}
              />
            </View>
          )
            : (<View style={{ flex: 1 }}>
              <PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this.onErrorRefresh} />
            </View>)
        }
        {this._renderApprove()}
        <RefuseModal
          titleText={'审批意见'}
          placeholderText={this.auditResult ? '请输入同意原因' : null}
          propsDefaultValue={this.auditResult ? '审批同意' : '审批驳回'}
          visible={showRejectModal}
          btnPress={(text) => {
            this.remark = text;
            this.approve();
          }}
          bgPress={() => {
            this.setState({
              showRejectModal: false,
            });
          }} />
        {/* 审批流 */}
        <ProgressModal {...lightBoxData} />
        <SlideSelect
          alertShow={alertShow}
          options={organs}
          titile='请选择对应部门'
          select={(val) => {
            this.setState({ branch: val || branch[0], alertShow: false, section: true, }, async () => {
              await this.initPage();
            })
          }}
          unselect={() => {
            this.setState({ alertShow: false })
          }} />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  flexBox: {
    flexDirection: 'row',
    backgroundColor: style.color.themeColor,
    paddingLeft: 25 * scale,
  },
  flexDate: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
  },
  flexMonth: {
    color: '#fff',
    fontSize: 12 * scale,
    opacity: 0.9,
  },
  flexDateTime: {
    color: '#fff',
    fontSize: 12 * scale,
    fontWeight: '500',
  },
  flexType: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
    paddingLeft: 110 * scale
  },
  flexBusiness: {
    color: '#fff',
    fontSize: 12 * scale,
    opacity: 0.9,
  },
  flexBranch: {
    color: '#fff',
    fontSize: 12 * scale,
    opacity: 0.9,
    marginBottom: 3 * scale

  },
  flexSection: {
    // flexDirection: 'row',
    marginTop: -2 * scale,
  },
  flexBranchtitle: {
    flexDirection: 'row',
    marginTop: -2 * scale,
  },
  flexSectionName: {
    color: '#fff',
    fontSize: 12 * scale,
    fontWeight: '500',
  },
  flexBranchText: {
    marginTop: -6 * scale,
  },
  flexBranchName: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
  },
  flexContent: {
    color: '#fff',
    fontSize: 12 * scale,
    fontWeight: '500',
  },
  flexRefer: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    backgroundColor: style.color.themeColor,
    // alignItems: 'center',
    paddingTop: 6 * scale,
    paddingLeft: 25 * scale,
  },
  flexClassify: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    backgroundColor: style.color.themeColor,
    paddingLeft: 49 * scale,
    paddingBottom: 30 * scale,
    paddingTop: -10 * scale,
    alignItems: 'center',
  },
  flexVaule: {
    color: '#fff',
    fontSize: 12 * scale,
    opacity: 0.9,
  },
  flexProuct: {
    color: '#fff',
    fontSize: 12 * scale,
    fontWeight: '500',
  },
  headBox: {
    // backgroundColor: style.color.themeColor,
    marginTop: -15 * scale,
    // height: 50 * scale,
    borderTopLeftRadius: 10 * scale,
    borderTopRightRadius: 10 * scale,
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: '#fff',
    backgroundColor: '#fff',
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'space-around',
    paddingLeft: 60 * scale,
    paddingRight: 60 * scale,
  },
  tabItems: {
    color: '#0E7FFD',
    fontSize: 12 * scale,
    // width: '35%',
    textAlign: 'center',
    marginTop: 20 * scale,
    opacity: .8,
    paddingRight: 5 * scale,
    paddingLeft: 5 * scale,
    paddingBottom: 5 * scale,
  },
  marginStyle: {
    marginLeft: 20 * scale,
    // marginRight: 16 * scale
  },
  tabItemActive: {
    opacity: 1,
  },
  stateView: {
    flexDirection: 'row',
    marginTop: 15 * scale,
    // marginBottom: 15 * scale,
    flexWrap: 'wrap'
  },
  stateItem: {
    padding: 8 * scale,
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    marginBottom: 15 * scale,
    borderColor: style.color.themeColor,
    borderRadius: 20 * scale,
    marginRight: 10 * scale,
    flexDirection: 'row'
  },
  stateItemText: {
    paddingRight: 4 * scale,
    paddingLeft: 4 * scale,
    fontSize: 11 * scale,
    color: style.color.themeColor
  },
  stateItemInfo: {
    width: 6 * scale,
    height: 6 * scale,
    backgroundColor: style.color.fontRed1,
    borderRadius: 3 * scale,
    position: 'relative',
    top: -5 * scale
  },
  stateItemActive: {
    backgroundColor: style.color.themeColor,
  },
  stateActive: {
    backgroundColor: style.color.white,
  },
  stateItemTextActive: {
    fontSize: 11 * scale,
    color: style.color.white
  },
  stateItemInfoActive: {
    backgroundColor: style.color.white
  },
  body: {
    flex: 1,
    backgroundColor: '#fff',
  },
  flexCount: {
    fontSize: 10 * scale,
    color: '#000000',
    opacity: 0.9
  },
  itemLightText: {
    fontSize: 12 * scale,
    color: '#000',
    // fontWeight: '500',
  },
  itemCause: {
    fontSize: 12 * scale,
    color: '#0091FF',
  },
  itemAccount: {
    fontSize: 12 * scale,
    color: '#272727',
  },
  itemDayTime: {
    justifyContent: 'flex-end',
    flex: 1,
    flexDirection: 'row'
  },
  itemTime: {
    fontSize: 12 * scale,
    color: '#272727',
    opacity: .8,
    paddingTop: 10 * scale,
    paddingRight: 10 * scale,
  },

  flexRow: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center'
  },

  lockView: {
    flexDirection: 'row',
    // justifyContent: 'center',
    alignItems: 'center',
    height: 12 * scale,
    width: 12 * scale,
    borderWidth: 1 * scale,
    borderColor: '#0E7FFD',
    // marginLeft: 14 * scale,
    marginRight: 5 * scale,
  },

  flexWhole: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
    paddingTop: 20 * scale,
    paddingLeft: 20 * scale,
    paddingBottom: 20 * scale,
    backgroundColor: style.color.bgGray,
  },
  consent: {
    paddingRight: 20 * scale,
    paddingLeft: 20 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
    fontSize: 12 * scale,
    opacity: 1,
    color: '#ffffff',
    alignItems: 'center',
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 15 * scale,
    // marginRight: 0 * scale,
    flexDirection: 'row',
    backgroundColor: style.color.themeColor,
    overflow: 'hidden'
  },
  itemdown: {
    fontSize: 12 * scale,
    color: style.color.themeColor,
    alignItems: 'center',
    paddingRight: 20 * scale,
    paddingLeft: 20 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 15 * scale,
    marginRight: 20 * scale,
    flexDirection: 'row',
    marginLeft: 10 * scale,
  },
  bodys: {
    paddingTop: 10 * scale,
    paddingBottom: 10 * scale,
  },
})